package pers.xx.sbm.utils.file;

import pers.xx.sbm.dao.DownloadErrorLogMapper;
import pers.xx.sbm.entity.DownloadErrorLog;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author ：xiexing
 * @description：网络图片下载
 * @date ：2021/2/1 10:29
 */
public class NetworkImgDownload {


    private DownloadErrorLogMapper downloadErrorLogMapper;

    private final static String netUrl = "http://tkbm.gyzkzx.cn/gyeducation";//网络路径

    private final static String destDirPath = "C:\\Users\\18359\\Desktop\\book\\download20200202";//目标图片路径

    public NetworkImgDownload(DownloadErrorLogMapper downloadErrorLogMapper) {
        this.downloadErrorLogMapper = downloadErrorLogMapper;
    }

    /**
     * @param imgUrl 图片路径
     * @param type   图片类型 1封面 2编目信息图片
     * @description 下载服务器图片
     * @author XieXing
     * @date 2021/2/1 11:00
     */
    public synchronized void download(String imgUrl, int type) {
        try {
            URL url = new URL(netUrl + imgUrl);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            String imageName = imgUrl.substring(imgUrl.lastIndexOf("/") + 1); //源文件名称
            String destFilePath = destDirPath + File.separator + imageName;
            FileOutputStream fileOutputStream = new FileOutputStream(new File(destFilePath));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            //文件不存在
            DownloadErrorLog downloadErrorLog = new DownloadErrorLog();
            downloadErrorLog.setPath(imgUrl);
            downloadErrorLog.setType(type);
            downloadErrorLog.setRemark("图片不存在四次查找不存在");
            downloadErrorLogMapper.insert(downloadErrorLog);
        }
    }
}
